package com.fullstack.server.util

import cats.*
import cats.implicits.*
import com.fullstack.common.domain.error.Unauthorized

import java.time.Instant
import io.circe.*
import jawn.parse as jawnParse
import pdi.jwt.{JwtAlgorithm, JwtCirce, JwtClaim}


/**
 *  JWT token生成和解析
 *
 *
 */


object TokenUtil {

  val key = "tokenSecretKey"
  val algo = JwtAlgorithm.HS256

  def generateToken(userId: String): String =
    val claim = JwtClaim(
      content = s"""{"userId":"${userId}"}""",
      expiration = Some(Instant.now.plusSeconds(157784760).getEpochSecond),
      issuedAt = Some(Instant.now.getEpochSecond)
    )
    val token = JwtCirce.encode(claim, key, algo)
    s"Bearer $token"

  def parseToken(token: String): Either[Unauthorized, String] =

    JwtCirce.decode(token, key, Seq(JwtAlgorithm.HS256)).fold(
      fa = _ => Unauthorized("验证失败，请先登录。").asLeft,
      fb = claim =>
        jawnParse(claim.content).fold(
          fa = _ => Unauthorized("验证解析失败。").asLeft,
          fb = claimJson => claimJson.hcursor.get[String]("userId").getOrElse("errorUserId").asRight
        )
    )


  def main(args: Array[String]): Unit = {


    val str = generateToken("sbaid8ssf")
    println(str)

    val userId = parseToken(str)
    println(userId)

  }


}